﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Configuration;
using System.Data;
using System.Net;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json;
using Model;
using BLL;
using HtmlAgilityPack;
using System.IO;
using System.IO.Compression;
using System.Text;
using System.Text.RegularExpressions;

namespace Inventory.view
{
    public partial class GoodsInfo : System.Web.UI.Page
    {
        public int sellerId;
        protected void Page_Load(object sender, EventArgs e)
        {
            Seller model = (Seller)Session["CurrentUser"];
            if (model == null)
            {
                //Response.Write("<script>alert(\"请登录系统\");window.location.href=\"login.aspx\"</script>");
                //Response.End();
            }
            //sellerId = model.Id;
            if (Request["action"] != null && Request["action"] == "getClass")
            {
                //获取分类
                GetClass();
            }
            else if (Request["action"] != null && Request["action"] == "getList")
            {
                GetInfoList();
            }
            else if (Request["action"] != null && Request["action"] == "save")
            {
                //保存
                Save();
            }
            else if (Request["action"] != null && Request["action"] == "del")
            {
                //删除
                Del();
            }
            else if (Request["action"] != null && Request["action"] == "getDtl")
            {
                //获得商品明细信息
                GetDtl();
            }
            else if (Request["action"] != null && Request["action"] == "savedtl")
            {
                SaveDtl();
            }
        }

        //保存明细数据
        private void SaveDtl()
        {
            GoodsInfoBll bll = new GoodsInfoBll();
            List<GoodsDtlInfo> list = new List<GoodsDtlInfo>();
            list = JsonConvert.DeserializeObject<List<GoodsDtlInfo>>(Request["jsonStr"]);
            bll.SaveDtl(list);
        }

        //获得明细
        private void GetDtl()
        {
            GoodsInfoBll bll = new GoodsInfoBll();
            GoodsDtlInfo m = new GoodsDtlInfo();
            List<GoodsDtlInfo> list = new List<GoodsDtlInfo>();
            list = bll.ListGoodsDtlInfo(Request["goodsId"]);
            string jsonText = JsonConvert.SerializeObject(list);
            Response.Write(jsonText);
            Response.End();
        }

        private void GetInfoList()
        {
            GoodsInfoBll bll = new GoodsInfoBll();
            MGoodsInfo m = new MGoodsInfo();
            if (!string.IsNullOrEmpty(Request["classId"]))
            {
                m.ClassId = Request["classId"].ToString() == "" ? 0 : Convert.ToInt32(Request["classId"].ToString());
            }
            if (!string.IsNullOrEmpty(Request["goodsName"]))
            {
                m.GoodsName = Request["goodsName"];
            }
            if (!string.IsNullOrEmpty(Request["no"]))
            {
                m.No = Request["no"];
            }
            List<MGoodsInfo> list = new List<MGoodsInfo>();
            list = bll.ListGoodsInfo(m);
            IsoDateTimeConverter timeConverter = new IsoDateTimeConverter();//对时间进行格式化
            timeConverter.DateTimeFormat ="yyyy-MM-dd HH:mm:ss";
            string jsonText = JsonConvert.SerializeObject(list, Formatting.Indented, timeConverter);
            Response.Write(jsonText);
            Response.End();
        }

        private void GetClass()
        {
            GoodsClassfyBll bllClass = new GoodsClassfyBll();
            List<MGoodsClassfy> list = new List<MGoodsClassfy>();
            MGoodsClassfy mclass = new MGoodsClassfy();
            mclass.SellerId = 0;//这里到时候要改成读取当前登录的店铺信息
            list = bllClass.ListClassByGroup(mclass);
            string jsonText = JsonConvert.SerializeObject(list);
            Response.Write(jsonText);
            Response.End();
        }

        private void Save()
        {
            try
            {
                GoodsInfoBll bll = new GoodsInfoBll();
                List<MGoodsInfo> list = new List<MGoodsInfo>();
                list = JsonConvert.DeserializeObject<List<MGoodsInfo>>(Request["jsonStr"]);
                HtmlDocument doc = new HtmlDocument();
                string html = "";
                string shopType = "";
                foreach (var li in list)
                {
                    if (string.IsNullOrEmpty(li.GoodsUrl))
                    {
                        continue;
                    }
                    html = HtmlStr(li.GoodsUrl, out shopType);
                    doc.LoadHtml(html);
                    li.GoodsName = Spmc(doc, shopType).Replace("\t", "").Replace("\r", "").Replace("\n", "");
                    li.PicSrc = PicSrc(doc, shopType);
                    li.LastUpdateTime = DateTime.Now;
                    li.ListGoodsDtlInfo = ListGoodsDtlInfo(li.GoodsId, doc, shopType);
                    li.SellerId = sellerId;
                }
                bll.Save(list);
                IsoDateTimeConverter timeConverter = new IsoDateTimeConverter();//对时间进行格式化
                timeConverter.DateTimeFormat = "yyyy-MM-dd HH:mm:ss";
                string jsonText = JsonConvert.SerializeObject(list, Formatting.Indented, timeConverter);
                Response.Clear();
                Response.Write(jsonText);
                Response.End();
            }
            catch (Exception ex)
            {

            }
        }

        /// <summary>
        /// 获得商品尺寸，颜色详细信息
        /// </summary>
        /// <param name="goodsId"></param>
        /// <param name="doc"></param>
        /// <param name="shopType"></param>
        /// <returns></returns>
        public List<GoodsDtlInfo> ListGoodsDtlInfo(string goodsId ,HtmlDocument doc, string shopType)
        {
            List<GoodsDtlInfo> list = new List<GoodsDtlInfo>();
            GoodsDtlInfo model;
            HtmlNode nodeColor = doc.DocumentNode.SelectSingleNode("//ul[@data-property='颜色']");
            HtmlNode nodeSize = doc.DocumentNode.SelectSingleNode("//ul[@data-property='尺码']");
            foreach (HtmlNode childColor in nodeColor.ChildNodes)//循环颜色
            {
                if (childColor.Attributes["title"] != null)
                {
                    string color = childColor.Attributes["title"].Value;
                    string colorPicSrc = ""; 
                    if (childColor.SelectSingleNode(".//a") != null && childColor.SelectSingleNode(".//a").Attributes["style"] != null)
                    {
                        colorPicSrc = childColor.SelectSingleNode(".//a").Attributes["style"].Value;
                    }
                    if (shopType == "taobao")
                    {
                        colorPicSrc = colorPicSrc == "" ? colorPicSrc : colorPicSrc.Substring(15, colorPicSrc.Length - 44);
                    }
                    else if (shopType == "tmall")
                    {
                        colorPicSrc = colorPicSrc == "" ? colorPicSrc : colorPicSrc.Substring(15, colorPicSrc.Length - 47);
                    }
                    foreach (HtmlNode childSize in nodeSize.ChildNodes)//循环尺码
                    {
                        if (childSize.SelectSingleNode(".//span") != null)
                        {
                            model = new GoodsDtlInfo();
                            string size = childSize.SelectSingleNode(".//span").InnerHtml;
                            model.GoodsId = goodsId;
                            model.Color = color;
                            model.Size = size;
                            model.ColorPicSrc = colorPicSrc;
                            list.Add(model);
                        }
                    }
                }
            }
            return list;
        }

        /// <summary>
        /// 获得图片的url
        /// </summary>
        /// <param name="doc"></param>
        /// <param name="shopType"></param>
        /// <returns></returns>
        private string PicSrc(HtmlDocument doc, string shopType)
        {
            HtmlNode node = null;
            node = doc.DocumentNode.SelectSingleNode("//ul[@id='J_UlThumb']").SelectNodes(".//img")[0];
            if (node.Attributes["src"] != null)
            {
                return node.Attributes["src"].Value;
            }
            else
            {
                return node.Attributes["data-src"].Value;
            }
        }

        /// <summary>
        /// 获得商品名称
        /// </summary>
        /// <param name="doc"></param>
        /// <param name="shopType"></param>
        /// <returns></returns>
        private string Spmc(HtmlDocument doc, string shopType)
        {
            HtmlNode node = null;
            if (shopType == "taobao")
            {
                node = doc.DocumentNode.SelectSingleNode("//h3[@class='tb-item-title']");
            }
            else if (shopType == "tmall")
            {
                node = doc.DocumentNode.SelectSingleNode("//h3[@data-spm]");
            }
            return node.InnerHtml;
        }

        private void Del()
        {
            try
            {
                GoodsInfoBll bll = new GoodsInfoBll();
                bll.Del(Request["ids"], 0);//最后这个0是当铺的登录人id
            }
            catch (Exception ex)
            {

            }
        }


        /// <summary>
        /// 将查询字符串解析转换为名值集合.
        /// </summary>
        /// <param name="queryString"></param>
        /// <returns></returns>
        public static NameValueCollection GetQueryString(string queryString)
        {
            return GetQueryString(queryString, null, true);
        }

        /// <summary>
        /// 将查询字符串解析转换为名值集合.
        /// </summary>
        /// <param name="queryString"></param>
        /// <param name="encoding"></param>
        /// <param name="isEncoded"></param>
        /// <returns></returns>
        public static NameValueCollection GetQueryString(string queryString, Encoding encoding, bool isEncoded)
        {
            queryString = queryString.Replace("?", "");
            NameValueCollection result = new NameValueCollection(StringComparer.OrdinalIgnoreCase);
            if (!string.IsNullOrEmpty(queryString))
            {
                int count = queryString.Length;
                for (int i = 0; i < count; i++)
                {
                    int startIndex = i;
                    int index = -1;
                    while (i < count)
                    {
                        char item = queryString[i];
                        if (item == '=')
                        {
                            if (index < 0)
                            {
                                index = i;
                            }
                        }
                        else if (item == '&')
                        {
                            break;
                        }
                        i++;
                    }
                    string key = null;
                    string value = null;
                    if (index >= 0)
                    {
                        key = queryString.Substring(startIndex, index - startIndex);
                        value = queryString.Substring(index + 1, (i - index) - 1);
                    }
                    else
                    {
                        key = queryString.Substring(startIndex, i - startIndex);
                    }
                    if (isEncoded)
                    {
                        result[MyUrlDeCode(key, encoding)] = MyUrlDeCode(value, encoding);
                    }
                    else
                    {
                        result[key] = value;
                    }
                    if ((i == (count - 1)) && (queryString[i] == '&'))
                    {
                        result[key] = string.Empty;
                    }
                }
            }
            return result;
        }

        /// <summary>
        /// 解码URL.
        /// </summary>
        /// <param name="encoding">null为自动选择编码</param>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string MyUrlDeCode(string str, Encoding encoding)
        {
            if (encoding == null)
            {
                Encoding utf8 = Encoding.UTF8;
                //首先用utf-8进行解码                      
                string code = HttpUtility.UrlDecode(str.ToUpper(), utf8);
                //将已经解码的字符再次进行编码. 
                string encode = HttpUtility.UrlEncode(code, utf8).ToUpper();
                if (str == encode)
                    encoding = Encoding.UTF8;
                else
                    encoding = Encoding.GetEncoding("gb2312");
            }
            return HttpUtility.UrlDecode(str, encoding);
        }

        public string HtmlStr(string url,out string shopType)
        {
            string inputString = url;
            Uri uri = new Uri(inputString);
            string queryString = uri.Query;
            NameValueCollection col = GetQueryString(queryString);
            string id = col["id"];
            string urlToCrawl;
            string host = string.Empty;
            string referer = string.Empty;
            if (inputString.LastIndexOf("item.taobao.com") > -1)  //淘宝明细
            {
                urlToCrawl = String.Format("http://item.taobao.com/item.htm?id={0}", id);
                host = "item.taobao.com";
                referer = "www.taobao.com";
                shopType = "taobao";
            }
            else   //天猫明细
            {
                urlToCrawl = String.Format("http://detail.tmall.com/item.htm?id={0}", id);

                host = "detail.tmall.com";
                referer = "www.tmall.com";
                shopType = "tmall";
            }

            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(urlToCrawl);
            req.Method = "GET";
            req.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.117 Safari/537.36";
            req.Referer = referer;
            req.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8";
            req.Headers.Add("Accept-Encoding", "gzip,deflate,sdch;");

            HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
            string htmlCharset = "GBK";
            Encoding htmlEncoding = Encoding.GetEncoding(htmlCharset);
            StreamReader sr = new StreamReader(new GZipStream(resp.GetResponseStream(), CompressionMode.Decompress), htmlEncoding);

            string respHtml = sr.ReadToEnd();
            return respHtml;
        }
    }
}
